package com.tchintech.pay.view.activity;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.lljjcoder.citypickerview.widget.CityPicker;
import com.tchintech.pay.R;
import com.tchintech.pay.adapter.ShoppingunitAdapter;
import com.tchintech.pay.delegate.ShoppingunitDeleagte;
import com.tchintech.pay.frame.presenter.ActivityPresenter;
import com.tchintech.pay.model.entity.HttpCode;
import com.tchintech.pay.model.entity.ShopUnit;
import com.tchintech.pay.net.OkhttpClientTest;
import com.tchintech.pay.utils.AppConst;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/19 0019.
 * 商户报件
 */

public class ShoppingunitActivity extends ActivityPresenter<ShoppingunitDeleagte> implements View.OnClickListener {
    private EditText et_pcd, et_businessLicenseType, et_contactPersonType;
    private PopupWindow mPopWindow;
    private ShoppingunitAdapter shoppingunitAdapter;
    private List<ShopUnit> list;
    private Map<String, String> map;
    private String url_sub = "MerchantsReported.submit";
    //省  市  区
    private String province = "";
    private String city = "";
    private String district = "";
    //商户全称

    private String fullName = "";
    //商户简称
    private String shortName = "";
    //证件编号
    private String businessLicense = "";
    //邮箱
    private String contactEmail = "";
    //详细地址
    private String address = "";
    private Handler handler;


    @Override
    protected void initView() {
        super.initView();
        viewDelegate.setTv_title("商户入驻");
        et_pcd = viewDelegate.getEdit(R.id.et_pcd);
        et_businessLicenseType = viewDelegate.getEdit(R.id.et_businessLicenseType);
        et_contactPersonType = viewDelegate.getEdit(R.id.et_contactPersonType);
        viewDelegate.setOnClickListener(this, R.id.et_pcd, R.id.bt_submit, R.id.et_businessLicenseType, R.id.iv_back, R.id.et_contactPersonType);
        handler();
    }


    @Override
    public void onClick(View v) {
        hideSoft();
        switch (v.getId()) {
            case R.id.et_pcd:
                //省市区三级联查
                showPcd();
                break;
            case R.id.et_businessLicenseType:
                //证件类型查询
                businessType();
                break;
            case R.id.et_contactPersonType:
                //联系人类型查询
                contactType();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_submit:
                juge();
                break;
        }
    }

    /**
     * 前台数据判断
     */
    private void juge() {
        fullName = viewDelegate.getEtStr(R.id.et_allname);
        shortName = viewDelegate.getEtStr(R.id.et_shortname);
        businessLicense = viewDelegate.getEtStr(R.id.et_buinessnumber);
        address = viewDelegate.getEtStr(R.id.et_address);
        contactEmail = viewDelegate.getEtStr(R.id.et_contactEmail);
        int full_length = fullName.length();
        if (!fullName.equals("") && full_length >= 5 && full_length <= 25) {
            if (!shortName.equals("")) {
                if (!et_businessLicenseType.getTag().toString().equals("")) {
                    if (!businessLicense.equals("")) {
                        if (!province.equals("")) {
                            if (!address.equals("")) {
                                if (!contactEmail.equals("")) {
                                    if (!et_contactPersonType.getTag().toString().equals("")) {
                                        submit();
                                    } else {
                                        showMsg("请选择联系人类型");
                                    }
                                } else {
                                    showMsg("邮箱不能为空");
                                }
                            } else {
                                showMsg("详细地址不能为空");
                            }
                        } else {
                            showMsg("地址不能为空");
                        }

                    } else {
                        showMsg("证件编号不能为空");
                    }
                } else {
                    showMsg("请选择证件类型");
                }
            } else {
                showMsg("商户简称不能为空");
            }
        } else {
            showMsg("商户名称输入不正确");
        }
    }

    private void handler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                hideProgressDialog();
                switch (msg.what) {
                    case HttpCode.networkabnormal:
                        showMsg("当前网络不可用");
                        break;
                    case HttpCode.http_failed:
                        showMsg("连接失败");
                        break;
                    case HttpCode.http_timeout:
                        showMsg("请求超时");
                        break;
                    case HttpCode.SHOPPING_BJ:
                        try {
                            JSONObject json = new JSONObject(msg.obj.toString());
                            if (json.getString("ret").equals("1")) {
                                showMsg("商户入住成功");
                                //处理接下来的问题
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                showMsg(json.getString("msg"));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
        };
    }

    /**
     * 提交
     */
    private void submit() {
        map = new HashMap<String, String>();
        map.put("fullName", fullName);
        map.put("shortName", shortName);
        map.put("businessLicense", businessLicense);
        map.put("businessLicenseType", et_businessLicenseType.getTag().toString());
        map.put("contactPersonType", et_contactPersonType.getTag().toString());
        map.put("province", province);
        map.put("city", city);
        map.put("district", district);
        map.put("address", address);
        map.put("contactEmail", contactEmail);
        map.put("user_id", AppConst.getUser().getId());
        showProgressDialog("", "加载中，请稍后...");
        new OkhttpClientTest().path(this, handler, url_sub, map, HttpCode.SHOPPING_BJ);

    }


    /**
     * 证件类型
     */
    private void businessType() {
        list = new ArrayList<ShopUnit>();
        String[] contType = {"NATIONAL_LEGAL：营业执照", "NATIONAL_LEGAL_MERGE：营业执照多证合一", "INST_RGST_CTF：事业单位法人证书"};
        for (int i = 0; i < contType.length; i++) {
            String[] str = contType[i].split("：");
            ShopUnit s = new ShopUnit();
            s.setName(str[0]);
            s.setAlias_name(str[1]);
            list.add(s);
        }
        showPopupWindow(1, list);
    }

    /**
     * 联系人选择类型
     */
    private void contactType() {
        list = new ArrayList<ShopUnit>();
        String[] contType = {"LEGAL_PERSON：法人", "CONTROLLER：实际控制人", "AGENT：代理人", "OTHER：其他"};
        for (int i = 0; i < contType.length; i++) {
            String[] str = contType[i].split("：");
            ShopUnit s = new ShopUnit();
            s.setName(str[0]);
            s.setAlias_name(str[1]);
            list.add(s);
        }
        showPopupWindow(2, list);
    }

    /**
     * 省市县选择
     */
    private void showPcd() {
        CityPicker cityPicker = new CityPicker.Builder(this)
                .textSize(16)
                .title("地址选择")
                .titleBackgroundColor("#FFFFFF")
                .confirTextColor("#696969")
                .cancelTextColor("#696969")
                .province("陕西省")
                .city("西安市")
                .district("碑林区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(10)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                province = citySelected[0];
                //城市
                city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                district = citySelected[2];
                //邮编
                String code = citySelected[3];

                //为TextView赋值
                et_pcd.setText(province.trim() + "-" + city.trim() + "-" + district.trim());


            }
        });
    }

    /**
     * 显示选择的popuwindow
     *
     * @param type
     * @param list
     */
    private void showPopupWindow(final int type, List<ShopUnit> list) {
        View v = LayoutInflater.from(this).inflate(R.layout.adapter_shoppingunit, null);
        mPopWindow = new PopupWindow(v, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(v);
        //设置背景
        ColorDrawable dw = new ColorDrawable(Color.parseColor("#ffffff"));
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setBackgroundDrawable(dw);
        ListView lv = (ListView) v.findViewById(R.id.lv_shopping);
        shoppingunitAdapter = new ShoppingunitAdapter(this, list);
        lv.setAdapter(shoppingunitAdapter);
        //显示PopupWindow
        backgroundAlpha(0.5f);
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_shoppingunit, null);
        //PopupWindow动画效果
        mPopWindow.setAnimationStyle(R.style.PopupAnimation);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);
        //popu的监听
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ShopUnit shopUnit = (ShopUnit) parent.getItemAtPosition(position);
                if (type == 1) {
                    et_businessLicenseType.setText(shopUnit.getAlias_name());
                    et_businessLicenseType.setTag(shopUnit.getName());
                } else {
                    et_contactPersonType.setText(shopUnit.getAlias_name());
                    et_contactPersonType.setTag(shopUnit.getName());

                }
                hide();
            }
        });
    }

    /**
     * 关闭PopupWindow
     */
    private void hide() {
        if (mPopWindow != null && mPopWindow.isShowing()) {
            mPopWindow.dismiss();
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    @Override
    protected Class<ShoppingunitDeleagte> getDelegateClass() {
        return ShoppingunitDeleagte.class;
    }
}

